package com.kanshu.ksgb.fastread.doudou.module.reader.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.google.gson.reflect.TypeToken;
import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.BookInfo;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.SimpleChapterBean;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.DiskLruCacheUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.JsonUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.StorageUtils;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.BookMark;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.ChapterBean;
import com.kanshu.ksgb.fastread.doudou.module.book.utils.SimpleChapterAdapter;
import com.kanshu.ksgb.fastread.doudou.module.reader.bean.BookRecordBean;
import com.kanshu.ksgb.fastread.doudou.module.reader.page.PageMode;
import com.kanshu.ksgb.fastread.doudou.module.reader.page.PageStyle;
import com.tencent.mmkv.MMKV;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


/**
 * 阅读设置相关配置
 */
public class SettingManager {
    public static final String SHARED_READ_PAGE_MODE = "shared_read_mode";
    public static final String SHARED_SCREEN_ON_PARAM = "screen_on_param";
    public static final String SHARED_EYE_SHIELD_MODE = "eye_shield_mode";
    public static final String READ_BOOK_SP = Constants.SP_NAME + "tmp";
    private volatile static SettingManager sManager;
    private SharedPreferences mPreferencesRead;
    private SharedPreferences mSharedPreferences;
    private SharedPreferences mReadBookPreferences;
    // 存书架的相关信息
    private List<BookInfo> mBookInfos;

    public static SettingManager getInstance() {
        if (sManager == null) {
            synchronized (SettingManager.class) {
                if (sManager == null) {
                    sManager = new SettingManager();
                }
            }
        }
        return sManager;
    }

    private SettingManager() {
        mSharedPreferences = Xutils.getContext().getSharedPreferences(Constants.SP_READ_NAME, Context.MODE_PRIVATE);
        mPreferencesRead = Xutils.getContext().getSharedPreferences(Constants.SP_NAME, Context.MODE_PRIVATE);
        mReadBookPreferences = Xutils.getContext().getSharedPreferences(READ_BOOK_SP, Context.MODE_PRIVATE);
    }

    /**
     * 保存书籍阅读字体大小
     *
     * @param bookId     需根据bookId对应，避免由于字体大小引起的分页不准确
     * @param fontSizePx
     * @return
     */
    public void saveFontSize(String bookId, int fontSizePx) {
        mPreferencesRead.edit().putInt(getFontSizeKey(bookId), fontSizePx).apply();
    }

    /**
     * 保存全局生效的阅读字体大小
     *
     * @param fontSizePx
     */
    public void saveFontSize(int fontSizePx) {
        saveFontSize("", fontSizePx);
    }

    public int getReadFontSize(String bookId) {
        //use dp
        return mPreferencesRead.getInt(getFontSizeKey(bookId), 19);
    }

    public int getReadFontSize() {
        return getReadFontSize("");
    }

    private String getFontSizeKey(String bookId) {
        return bookId + "-readFontSize";
    }

    public int getReadBrightness() {
        return mPreferencesRead.getInt(getLightnessKey(), (int) DisplayUtils.getScreenBrightness(Xutils.getContext()));
    }

    /**
     * 保存阅读界面屏幕亮度
     *
     * @param percent 亮度比例 0~100
     */
    public void saveReadBrightness(int percent) {
        mPreferencesRead.edit().putInt(getLightnessKey(), percent).commit();
    }

    private String getLightnessKey() {
        return "readLightness";
    }

    private String getChapterKey(String bookId) {
        return bookId + "-chapter";
    }
    private String getPosKey(String bookId) {
        return bookId + "pos";
    }
    private String getStartPosKey(String bookId) {
        return bookId + "-startPos";
    }


    /**
     * 添加书签
     *
     * @param bookId
     * @param mark
     * @return
     */
    public boolean addBookMark(String bookId, BookMark mark) {
        Type type = new TypeToken<List<BookMark>>() {
        }.getType();
        List<BookMark> marks = DiskLruCacheUtils.get(getBookMarksKey(bookId), type);
        if (marks != null && marks.size() > 0) {
            for (BookMark item : marks) {
                if (item.chapter == mark.chapter && item.position == mark.position) {
                    return false;
                }
            }
        } else {
            marks = new ArrayList<>();
        }
        marks.add(mark);
        DiskLruCacheUtils.put(getBookMarksKey(bookId), marks);
        return true;
    }

    /**
     * 移除书签
     *
     * @param bookId
     * @param mark
     */
    public void removeBookMarkForOldReader(String bookId, BookMark mark) {
        Type type = new TypeToken<List<BookMark>>() {
        }.getType();
        List<BookMark> marks = DiskLruCacheUtils.get(getBookMarksKey(bookId), type);
        if (marks != null && marks.size() > 0) {
            for (int i = marks.size() - 1; i >= 0; i--) {
                BookMark item = marks.get(i);
                if (item.chapter == mark.chapter
                        && item.startPos == mark.startPos) {
                    marks.remove(i);
                }
            }
        } else {
            marks = new ArrayList<>();
        }
        DiskLruCacheUtils.put(getBookMarksKey(bookId), marks);
    }

    public List<BookMark> getBookMarks(String bookId) {
        Type type = new TypeToken<List<BookMark>>() {
        }.getType();
        return DiskLruCacheUtils.get(getBookMarksKey(bookId), type);
    }

    public void clearBookMarks(String bookId) {
        DiskLruCacheUtils.put(getBookMarksKey(bookId), new ArrayList<BookMark>());
    }

    /**
     * 获取书签的key
     * @param bookId
     * @return
     */
    private String getBookMarksKey(String bookId) {
        return getBookPrefix() + bookId + "-marks";
    }

    public void saveReadTheme(int theme) {
        mPreferencesRead.edit().putInt("readTheme", theme).commit();
    }

    public int getReadTheme() {
        return mPreferencesRead.getInt("readTheme", 3);
    }

    /**
     * 是否可以使用音量键翻页
     *
     * @param enable
     */
    public void saveVolumeFlipEnable(boolean enable) {
        mPreferencesRead.edit().putBoolean("volumeFlip", enable).apply();
    }

    public boolean isVolumeFlipEnable() {
        return mPreferencesRead.getBoolean("volumeFlip", true);
    }

    public void saveAutoBrightness(boolean enable) {
        mPreferencesRead.edit().putBoolean("autoBrightness", enable).apply();
    }

    public boolean isAutoBrightness() {
        return mPreferencesRead.getBoolean("autoBrightness", true);
    }

    public boolean isNight() {
        return mPreferencesRead.getBoolean("isNight", false);
    }

    public void saveIsNight(boolean isNight) {
        mPreferencesRead.edit().putBoolean("isNight", isNight).commit();
    }

    /**
     * 获取章节总数
     * @param bookId
     * @return
     */
    public int getChapterCount(String bookId) {
        int count = mPreferencesRead.getInt("chapter_count@new" + bookId,0);
        if (count != 0) {
            return count;
        }
        count = getBookChapterCount(bookId);
        if (count != 0) {
            return count;
        }
        SimpleChapterBean simpleChapterInfo = getSimpleChapterInfo(bookId, 1);
        if (simpleChapterInfo != null) {
            return Integer.parseInt(simpleChapterInfo.chapter_count);
        }
        return 0;
    }

    /**
     * @param bookId
     * @param chapterIndex
     * @return
     */
    public String getCurBookChapterTitle(String bookId, int chapterIndex) {
        SimpleChapterBean simpleChapterInfo = getSimpleChapterInfo(bookId, chapterIndex);
        if (simpleChapterInfo != null) {
            return simpleChapterInfo.title;
        }
        return "";
    }

    /**
     * @param bookId
     * @param chapterIndex
     * @return
     */
    public String getCurBookTitle(String bookId, int chapterIndex) {
        SimpleChapterBean simpleChapterInfo = getSimpleChapterInfo(bookId, chapterIndex);
        if (simpleChapterInfo != null) {
            return simpleChapterInfo.book_title;
        }
        return "";
    }

    public void saveTabDot(int tabIndex, int dotNum) {
        mPreferencesRead.edit().putInt(getBookPrefix() + tabIndex + "-dot", dotNum).apply();
    }

    public void saveTabDot(int tabIndex) {
        saveTabDot(tabIndex, 0);
    }

    public int getTabDot(int tabIndex) {
        return mPreferencesRead.getInt(getBookPrefix() + tabIndex + "-dot", -1);
    }

    /**
     * 保存书架列表
     * @param list
     */
    public void saveShelfInfos(List<BookInfo> list) {
        mBookInfos = list;
    }

    /**
     * 获取书架列表
     * @return
     */
    public List<BookInfo> getShelfInfos() {
        return mBookInfos;
    }

    /**
     * 获取当前用户的书架数据信息
     * @return
     */
    public List<BookInfo> getShelfInfosFromSd() {
        Type type = new TypeToken<ArrayList<BookInfo>>() {
        }.getType();
        // 本地缓存数据
        String key = getShelfBookKey();
        mBookInfos = DiskLruCacheUtils.get(key, type);
        return mBookInfos;
    }

    /**
     * 保存简单章节信息
     * @param bookId
     * @param chapterIndex
     * @param bean
     */
    public void saveSimpleChapterInfo(String bookId, int chapterIndex, ChapterBean bean) {
        saveSimpleChapterInfoByMMKV(bookId, chapterIndex, bean);
    }

    /**
     * 保存简单章节信息
     * @param bookId
     * @param chapterIndex
     * @param bean
     */
    public void saveSimpleChapterInfo(String bookId, int chapterIndex, SimpleChapterBean bean) {
        saveSimpleChapterInfoByMMKV(bookId, chapterIndex, bean);
    }

    /**
     * 获取简单章节信息
     * @param bookId
     * @param chapterIndex
     * @return
     */
    public SimpleChapterBean getSimpleChapterInfo(String bookId, int chapterIndex) {
        return getSimpleChapterInfoByMMKV(bookId, chapterIndex);
    }

    /**
     * 保存简单章节信息
     * @param bookId
     * @param chapterIndex
     * @param bean
     */
    public void saveSimpleChapterInfoByMMKV(String bookId, int chapterIndex, ChapterBean bean) {
        SimpleChapterBean bean1 = SimpleChapterAdapter.changeToSimpleChapter(bean);
        saveSimpleChapterInfoByMMKV(bookId, chapterIndex, bean1);
    }

    /**
     * 保存简单章节信息
     * @param bookId
     * @param chapterIndex
     * @param bean
     */
    public void saveSimpleChapterInfoByMMKV(String bookId, int chapterIndex, SimpleChapterBean bean) {
        MMKV bookMMKV = MMKVDefaultManager.getInstance().getBookMMKV(bookId);
        bookMMKV.edit()
                .putString("simple_chapter" + bookId + "@" + chapterIndex, JsonUtils.bean2JsonByFastJson(bean))
                .putString("chapter_count" + bookId, bean.chapter_count)
                .apply();
    }

    /**
     * 获取简单章节信息
     * @param bookId
     * @param chapterIndex
     * @return
     */
    public SimpleChapterBean getSimpleChapterInfoByMMKV(String bookId, int chapterIndex) {
        MMKV bookMMKV = MMKVDefaultManager.getInstance().getBookMMKV(bookId);
        String s = bookMMKV.getString("simple_chapter" + bookId + "@" + chapterIndex, "");
        if (TextUtils.isEmpty(s)) {
            return null;
        }
        return JsonUtils.json2BeanByFastJson(s, SimpleChapterBean.class);
    }

    /**
     * 获取书籍标题
     * @param bookId
     * @param chapterIndex
     * @return
     */
    public String getBookTitle(String bookId, int chapterIndex) {
        SimpleChapterBean info = getSimpleChapterInfo(bookId, chapterIndex);
        if (info != null) {
            return info.book_title;
        }
        return "";
    }

    public boolean isFirstHomeView() {
        return StorageUtils.getPreference(Xutils.getContext(), Constants.SP_NAME, getBookPrefix() + "first_home_view", false);
    }

    public boolean isFirstVipShow(String bookId) {
        return StorageUtils.getPreference(Xutils.getContext(), Constants.SP_NAME + "is_vip", getBookPrefix() + "simple_chapter" + bookId + "is_vip", false);
    }

    public void setFirstVipShow(String bookId, boolean flg) {
        StorageUtils.setPreference(Xutils.getContext(), Constants.SP_NAME + "is_vip", getBookPrefix() + "simple_chapter" + bookId + "is_vip", flg);
    }

    public boolean isFirstEntryReader() {
        return mPreferencesRead.getBoolean(getBookPrefix() + Constants.IS_FIRST_ENTRY_READER + "new", true);
    }

    public void saveFirstEntryReader(boolean flg) {
        mPreferencesRead.edit().putBoolean(getBookPrefix() + Constants.IS_FIRST_ENTRY_READER + "new", flg).apply();
    }

    /**
     * 用户是否之前读过
     * @param bookId
     * @return
     */
    public boolean isReadBook(String bookId) {
        return mReadBookPreferences.getBoolean(getBookPrefix() + bookId + Constants.IS_READ, false);
    }

    /**
     * 保存阅读标记
     * @param bookId
     * @param flg
     */
    public void saveReadBook(String bookId, boolean flg) {
        mReadBookPreferences.edit().putBoolean(getBookPrefix() + bookId + Constants.IS_READ, flg).apply();
    }
    /**
     * 桌面图标打红点
     * @return
     */
    public String getBadgeDate() {
        return mPreferencesRead.getString(getBookPrefix() + "badge_date", "");
    }

    public void saveBadgeDate(String date) {
        mPreferencesRead.edit().putString(getBookPrefix() + "badge_date", date).apply();
    }

    /**
     * 保存用户阅读时间
     */
    public void saveReadTime(long time) {
        mPreferencesRead.edit().putLong(getBookPrefix() + "read_time", time).apply();
    }

    public long getReadTime() {
        return mPreferencesRead.getLong(getBookPrefix() + "read_time", 0);
    }

    /**
     * 获取阅读记录
     * @param bookId
     * @return
     */
    public BookRecordBean getCurReadProgress(String bookId) {
        BookRecordBean recordBean = getCurReadProgressByMMKV(bookId);
        if (recordBean.chapter == 0) {
            int lastChapter = mPreferencesRead.getInt(getChapterKey(bookId), 1);
            int pos = mPreferencesRead.getInt(getPosKey(bookId), 0);
            int startPos = mPreferencesRead.getInt(getStartPosKey(bookId), 0);
            if (pos <= 0) {
                int lastChapterTmp = mSharedPreferences.getInt(getChapterKey(bookId), 1);
                if (lastChapterTmp != 1 && lastChapterTmp != lastChapter && lastChapter == 1) {
                    pos = mSharedPreferences.getInt(getPosKey(bookId), 0);
                    startPos = mSharedPreferences.getInt(getStartPosKey(bookId), 0);
                    lastChapter = lastChapterTmp;
                }
            }
            recordBean.bookId = bookId;
            recordBean.chapter = lastChapter;
            recordBean.itemPos = pos;
            recordBean.startPos = startPos;
        }
        return recordBean;
    }

    public synchronized void saveReadProgress(BookRecordBean item) {
        saveReadProgress(item.bookId, item.chapter, item.itemPos);
    }

    /**
     * 保存用户阅读记录
     * @param bookId
     * @param currentChapter
     * @param pos
     */
    public synchronized void saveReadProgress(String bookId, int currentChapter, int pos) {
        saveReadProgressByMMKV(bookId, currentChapter, pos);
    }
    public synchronized void saveReadProgressByMMKV(String bookId, int currentChapter, int pos) {
        MMKV mmkv = MMKVDefaultManager.getInstance().getUserMMKV();
        mmkv.edit().putInt(getChapterKey(bookId), currentChapter).putInt(getPosKey(bookId), pos).apply();
    }

    /**
     * 获取本地阅读记录
     * @param bookId
     * @return
     */
    public BookRecordBean getCurReadProgressByMMKV(String bookId) {
        MMKV mmkv = MMKVDefaultManager.getInstance().getUserMMKV();
        int lastChapter = mmkv.getInt(getChapterKey(bookId), 0);
        int startPos = mmkv.getInt(getStartPosKey(bookId), 0);
        int pos = mmkv.getInt(getPosKey(bookId), 0);
        BookRecordBean recordBean = new BookRecordBean();
        recordBean.bookId = bookId;
        recordBean.chapter = lastChapter;
        recordBean.itemPos = pos;
        recordBean.startPos = startPos;
        return recordBean;
    }

    public PageMode getPageMode() {
        int mode = mSharedPreferences.getInt(SHARED_READ_PAGE_MODE, PageMode.SIMULATION.ordinal());
        return PageMode.values()[mode];
    }

    public PageStyle getPageStyle() {
        int readTheme = mPreferencesRead.getInt("readTheme", 3);
        return PageStyle.values()[readTheme];
    }

    public void setPageStyle(PageStyle pageStyle) {
        mPreferencesRead.edit().putInt("readTheme", pageStyle.ordinal()).commit();
    }

    public void setPageMode(PageMode mode) {
        mSharedPreferences.edit().putInt(SHARED_READ_PAGE_MODE, mode.ordinal()).commit();
    }

    /**
     * 设置屏幕常亮时间参数
     *
     * @param param
     */
    public void setScreenOnParam(int param) {
        mPreferencesRead.edit().putInt(SHARED_SCREEN_ON_PARAM, param).apply();
    }

    /**
     * 获取屏幕常亮参数
     *
     * @return
     */
    public int getScreenOnParam() {
        return mPreferencesRead.getInt(SHARED_SCREEN_ON_PARAM, Constants.ScreenOnParams.SCREEN_ON_5_MIN);
    }

    /**
     * 是否是护眼模式
     *
     * @return
     */
    public boolean isEyeShieldMode() {
        return mPreferencesRead.getBoolean(SHARED_EYE_SHIELD_MODE, false);
    }

    /**
     * 设置护眼模式
     *
     * @param flg
     */
    public void setEyeShieldMode(boolean flg) {
        mPreferencesRead.edit().putBoolean(SHARED_EYE_SHIELD_MODE, flg).apply();
    }

    /**
     * 获取书籍缓存 userID前缀
     */
    public static String getBookPrefix() {
        String userId = UserUtils.getUserId();
        String defaultUserId = MMKVDefaultManager.getInstance().getDeviceUserId();
        return TextUtils.equals(userId, defaultUserId) ? "" : (userId + "_");
    }

    /**
     * 获取本地书架缓存的key
     * @return
     */
    public static String getShelfBookKey() {
        return UserUtils.getUserId() + "shelf_collect";
    }
    /**
     * 保存书的章节总数
     */
    public void saveBookChapterCount(String bookId, int count) {
        MMKVDefaultManager.getInstance().getDefaultMMKV().edit().putInt(bookId + "@count", count).apply();
    }

    /**
     * 获取书的章节总数
     */
    public int getBookChapterCount(String bookId) {
        return MMKVDefaultManager.getInstance().getDefaultMMKV().getInt(bookId + "@count", 0);
    }
}
